import React, { Component } from 'react'
import {
    Card, Breadcrumb, Form, Button, Radio, Select, DatePicker, Table, Tag, Modal
} from 'antd'
import { Link } from 'react-router-dom'
import { getChannels, getArticles, delArticle } from '../../api/user'
import defaultImg from '../../assets/error.png'
import { EditOutlined } from '@ant-design/icons';
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker
const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
]


export default class ArticleList extends Component {
    state = {
        channels: [],
        articles: [],
        total: 0,
        page: 1,
        per_page: 10,
    }
    columns = [
        {
            title: '封面',
            render(item) {
                // 情况1：无图，渲染默认图片
                // 情况2：有图，渲染第一张图片
                return (
                    <img
                        src={item.cover.type === 0 ? defaultImg : item.cover.images[0]}
                        title={item.title}
                        alt={item.title}
                        style={{ width: 100, height: 60, objectFit: 'cover' }}
                    />
                )
            },
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'age',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (status) => {
                const tagInfo = articleStatus.find(item => item.id === status);
                return <Tag color={tagInfo.color}>{tagInfo.name}</Tag>
            },
        },
        {
            title: '发布时间',
            key: 'tags',
            dataIndex: 'pubdate',
        },
        {
            title: '阅读数',
            dataIndex: 'read_count',
        },
        {
            title: '评论数',
            dataIndex: 'comment_count',
        },
        {
            title: '点赞数',
            dataIndex: 'like_count',
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <>
                        <Button
                            shape="circle"
                            type="primary"
                            icon={<EditOutlined />}
                            style={{ marginRight: 5 }}
                            onClick={() => this.handleEdit(item.id)}
                        ></Button>
                        <Button type="primary" shape="circle" danger icon={<DeleteOutlined />} onClick={() => this.handleDelete(item.id)}></Button>
                    </>
                );
            },
        },
    ]
    // 编辑
    handleEdit = (id) => {
        console.log(96, id);
        this.props.history.push(`/home/publish/${id}`)
    }
    async getChannelList() {
        const res = await getChannels()
        this.setState({
            channels: res.data.channels,
        })

    }
    async getArticleList() {
        const res = await getArticles()
        this.setState({
            articles: res.data.results,
            total: res.data.total_count,
        })
    }
    // 分页功能
    changePage = async (page, pageSize) => {
        const res = await getArticles({
            ...this.params,
            page,
            per_page: this.state.articles.per_page,
        })
        this.setState({
            articles: res.data,
        })
    }
    // 表单筛选功能
    onFinish = async (values) => {
        console.log(126, values)
        // 发送请求，获取数据
        const params = {}

        // 处理状态
        if (values.status !== -1) {
            params.status = values.status
        }
        console.log(127, params);

        // 处理频道
        if (values.channel_id) {
            params.channel_id = values.channel_id
        }
        // 处理日期
        // if (values.date) {
        //     params.begin_pubdate = values.date[0].format('YYYY-MM-DD')
        //     params.end_pubdate = values.date[1].format('YYYY-MM-DD')
        // }
        // 处理日期优化
        if (values.date) {
            params.begin_pubdate = values.date[0]
                .startOf('day')
                .format('YYYY-MM-DD HH:mm:ss')
            params.end_pubdate = values.date[1]
                .endOf('day')
                .format('YYYY-MM-DD HH:mm:ss')
        }
        params.page = 1
        this.params = params
        const res = await getArticles(params)
        console.log(140, res.data)
        this.setState({
            articles: res.data.results,
            total: res.data.total_count,
        })
    }
    // 删除按钮
    handleDelete = (id) => {
        confirm({
            title: '温馨提示？',
            icon: <ExclamationCircleOutlined />,
            content: '你确定要删除文章吗',
            onOk: async () => {
                // 发送请求进行删除
                await delArticle(id)
                this.getArticleList(this.params)
            },
        })
    }
    componentDidMount() {
        this.getChannelList()
        this.getArticleList()
    }
    render() {
        return (
            <Card title={
                <Breadcrumb separator="/">
                    <Breadcrumb.Item>
                        <Link to="/home">首页</Link>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>文章列表</Breadcrumb.Item>
                </Breadcrumb>
            }>
                <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
                    <Form.Item label="状态" name="status">
                        <Radio.Group>
                            <Radio value={-1}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>审核通过</Radio>
                            <Radio value={3}>审核失败</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="频道" name="channel_id">
                        <Select placeholder="请选择频道" style={{ width: 200 }}>
                            {this.state.channels.map((item) => (
                                <Option key={item.id} value={item.id}>{item.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="日期" name="password">
                        <RangePicker />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            筛选
                        </Button>
                    </Form.Item>
                </Form>
                <div className="articleList">
                    {/* <Card title={`根据筛选条件共查询到${0}条数据`}>
                        <Table dataSource={data} columns={columns} />
                    </Card> */}
                    <Card title={`根据筛选条件共查询到${this.state.total}条数据`}>
                        <Table
                            rowKey="id"
                            dataSource={this.state.articles}
                            columns={this.columns}
                            pagination={{
                                position: ['bottomCenter'],
                                current: this.state.page,
                                pageSize: this.state.per_page,
                                total: this.state.total,
                                // 每页大小 或者 页码 改变时，触发的事件
                                onChange: this.changePage,
                            }}
                        />
                    </Card>
                </div>
            </ Card>
        )
    }
}